package com.example.demo.Comm;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class PasswordUtils {
    public static String encrypt(String password) {
        String salt = UUID.randomUUID().toString().replace("-","");
        String finalPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+"$"+finalPassword;
    }

    public static boolean decrypt(String password,String dbPassword) {
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(dbPassword) || dbPassword.length() != 65) {
            return false;
        }
        String[] dpPasswordArray = dbPassword.split("\\$");
        if(dpPasswordArray.length != 2) {
            return false;
        }
        String salt = dpPasswordArray[0];
        String TruePassword = dpPasswordArray[1];
        if(TruePassword.equals(DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8)))) {
            return true;
        }

        return false;
    }
}
